import type { RouteRecordRaw } from 'vue-router';
import { createRouter, createWebHistory } from 'vue-router';
import { MetaDefaultValue } from '@/routes/MetaModule';
import { mainStore } from '@/store/main';
import i18n from '@/lang/i18nSetup';
import { showNotify } from 'vant';

import {
    getStorageItem,
    getToken,
    removeAllStorage,
    setStorageItem,
    setToken,
} from '@utils/StorageManager';
import {
    getAppEnvironment,
    getKumianmeiToken,
    reportEvent,
    reportPageView,
    closeWebview,
} from '@utils/NativeUtils';

import { getUserInfo as httpGetUserInfo } from '@api/main';
// import ALiLog from '@utils/LogUtils';
import axios from 'axios';
import { loadMessagesAsync } from '../lang/loadMessagesAsync';
import routesMap from './routesMap';

const basePath = '/to-h5';
const _routesMap = routesMap.map((route) => {
    const { noBasePath = false } = route.meta;
    return {
        ...route,
        path: (noBasePath ? '' : basePath) + route.path,
        meta: { ...MetaDefaultValue, ...route.meta },
    };
});
const router = createRouter({
    history: createWebHistory(),
    routes: <RouteRecordRaw[]>_routesMap,
    strict: true,
    scrollBehavior: () => ({ left: 0, top: 0 }),
});

router.beforeEach(async (to, from, next) => {
    const store = mainStore();
    // 为了适配IOS4.5.5以下版本，房间插件页需要手动拼接客户端语言，4.5.5以上版本client-language会传值两次（数组格式）
    const queryLang = Array.isArray(to.query['client-language'])
        ? to.query['client-language']?.[0]
        : to.query['client-language'];
    const lang = `${queryLang || window.sessionStorage.getItem('language') || 'en'}`;
    store.$SET_LANG(lang);
    const { t, te, getLocaleMessage, setLocaleMessage } = i18n.global;

    // 按需引入本地对应页面的翻译文件, 依次尝试读取route.meta.t / route.meta.pageTitle  / route.name对应的翻译文件
    async function loadCurrentPageTranslationFile() {
        const tArray = [];
        if (Array.isArray(to?.meta?.t)) {
            to.meta.t.forEach((name) => {
                if (typeof name === 'string' && !tArray.includes(name)) {
                    tArray.push(name);
                }
            });
        } else if (typeof to?.meta?.t === 'string') {
            tArray.push(to.meta.t);
        } else {
            typeof to?.meta?.pageTitle === 'string' &&
                to.meta.pageTitle !== 'Kumianmei' &&
                tArray.push(to.meta.pageTitle);
            typeof to?.name === 'string' && !tArray.includes(to.name) && tArray.push(to.name);
        }
        const messagesTasks = [];
        tArray.forEach((fileName) => {
            if (fileName) {
                messagesTasks.push(
                    new Promise((resolve) => {
                        loadMessagesAsync(fileName).then((file) => {
                            resolve(file);
                        });
                    })
                );
            }
        });
        // 将获取到的文件内容追加到i18n中
        await Promise.all(messagesTasks).then((files) => {
            files.forEach((file) => {
                if (typeof file === 'object') {
                    Object.entries(file).forEach(([key, value]) => {
                        const targetLanguage = key.replace('lang_', '');
                        const targetLanguageMessages = getLocaleMessage(targetLanguage);
                        setLocaleMessage(targetLanguage, {
                            ...targetLanguageMessages,
                            [String(file.tName)]: value,
                        });
                    });
                }
            });
        });
    }
    // if (
    //     /(?<=Kumianmei-frankfurt.oss-accelerate.aliyuncs.com\/web\/).+(?=.json)/.test(
    //         to?.meta?.t as any
    //     )
    // ) {
    //     // t指定了云端的页面翻译文件
    //     try {
    //         const { data: rawJson } = await axios.create().get(to.meta.t as string);
    //         const prefix = (to.meta.t as string).match(/(?<=\/)[^\/]+(?=\/lang.json)/g)[0];
    //         Object.entries(rawJson).forEach(([key, value]) => {
    //             const targetLanguageMessages = getLocaleMessage(key);
    //             setLocaleMessage(key, {
    //                 ...targetLanguageMessages,
    //                 [prefix]: value,
    //             });
    //         });
    //     } catch (e) {
    //         await loadCurrentPageTranslationFile();
    //     }
    // } else {
    //     // 没有指定云端文件，则从本地按需引入
    //     await loadCurrentPageTranslationFile();
    // }
    await loadCurrentPageTranslationFile();

    // 设置标题
    if (to.meta.pageTitle) {
        const _title: string =
            (te(`pageTitle.${to.meta.pageTitle}`)
                ? t(`pageTitle.${to.meta.pageTitle}`)
                : <string>to.meta.pageTitle) ?? 'Kumianmei';
        store.$SET_TITLE(_title);
    }

    if (to.meta.skeleton) {
        store.$SET_SKELETON_LOADING(true);
    }
    if (to.query?.vc === '1') {
        setStorageItem('vc', '1');
    }
    if (to.query?.hv && !document.querySelector('html').classList.contains('hideVconsole')) {
        document.querySelector('html').classList.add('hideVconsole');
    }
    if (to.meta.intercept !== '1') {
        window['onBackInterceptor'] = closeWebview;
    } else {
        // eslint-disable-next-line @typescript-eslint/no-empty-function
        window['onBackInterceptor'] = () => {};
    }
    if (!to.meta.keepAlive && !store.keepAliveExcludeComponents.includes(to.name)) {
        store.keepAliveExcludeComponents.push(to.name);
    }

    // 设置url携带的token
    const _token = getToken(); // 获取缓存的token
    if (to.query.token && to.query.token.length >= 32) {
        if (_token && _token !== to.query.token) {
            removeAllStorage(); // 对比，不一致则移除缓存的信息
        }
        setToken(`${to.query.token}`); // 重新缓存token
    } else if (!_token) {
        // 若url没有携带，缓存也没有token
        // 尝试调用客户端的方法获取token
        try {
            // TODO:暂时注释
            // const token = await getKumianmeiToken();
            // setToken(token);
        } catch (e) {
            console.error(e, '获取Token失败');
        }
    }

    // 路由是否需要登录才能访问
    if (to.meta.requireAuth && !getToken()) {
        showNotify({ duration: 0, message: 'Invalid User Login' });
        setStorageItem('errorRoute', { BrowserUrl: window.location.href, ...to });
        reportEvent(
            'KumianmeiH5',
            '跳转404',
            `[原因：未登录无效的用户token][跳转路径：${to.path}]`
        );
        // ALiLog.reportRoute(to.path, '未登录', true);
        next('/404');
        return;
    }

    // 如果缓存里没有登录信息，则请求接口
    if (getToken() && !getStorageItem('userInfo')) {
        try {
            const data = await httpGetUserInfo();
            store.$SET_USERID(data?.displayUserId);
            setStorageItem('userInfo', JSON.stringify(data));
        } catch (e) {
            showNotify({ duration: 0, message: e.message });
            if (to.meta.requireAuth) {
                setStorageItem('errorRoute', { BrowserUrl: window.location.href, ...to });
                reportEvent(
                    'KumianmeiH5',
                    '跳转404',
                    `[原因：获取用户信息接口(getUserInfo)请求失败][跳转路径：${to.path}]`
                );
                // ALiLog.reportRoute(to.path, '获取用户信息接口(getUserInfo)请求失败', true);
                next('/404');
                return;
            }
        }
    }

    if (import.meta.env.PROD && to.meta.mustBeInApp === true) {
        // 环境判断
        getAppEnvironment(to.query)
            .then((env) => {
                if (env.toString().toUpperCase() === 'Kumianmei') {
                    // ALiLog.reportRoute(to.path, '正常访问');
                    next();
                } else {
                    // ALiLog.reportRoute(to.path, '非KumianmeiApp内打开了URL');
                    next('/error-tip');
                }
            })
            .catch(() => {
                // ALiLog.reportRoute(to.path, '非KumianmeiApp内打开了URL');
                next('/error-tip');
            });
    } else {
        if (to.name === 'Error') {
            setStorageItem(
                'errorRoute',
                JSON.stringify({
                    reason: '404: 路由不存在',
                    ...to,
                })
            );
            // ALiLog.reportRoute(to.path, '路由不存在', true);
        } else {
            // ALiLog.reportRoute(to.path, '正常访问');
        }
        next();
    }

    // 上报埋点
    reportPageView(
        te(`pageTitle.${to.meta.pageTitle}`)
            ? t(`pageTitle.${to.meta.pageTitle}`)
            : <string>to.meta.pageTitle,
        undefined,
        to.path
    );
});

router.afterEach(() => {
    mainStore().$SET_SKELETON_LOADING(false);
});

export default router;
